// 说明：本文件中定义接口函数
// 其他js文件如需使用，请在其文件中使用形如 var my_interface = require("../../utils/interface") 的语句导入。
// 注意根据相对于js文件的相对路径的不同，参数路径可能不同

// 此处要填入所有需要使用的接口函数名，以导出为模块
module.exports = {
  login,
  register,
  has_login,
  logout,
  queryUserInfo,
  updateUserInfo,
  addVehicle,
  queryVehicle,
  updateVehicle,
  init_http_head,
  change_http_head,
  get_http_head,
  queryHistoryOrderList,
  queryCurrentOrder,
  createOrder,
  updateOrder,
  cancelOrder
}
let HTTPS_HEAD = ""
let buff_token = ""
const DEFAULT_HEAD = "http://10.128.214.252:8080"
const TIMEOUT = 5000

const URLS = {
  register: "/client/register",
  login: "/client/login",
  user_info: "/client/index/information",
  order: "/client/index/order",
  car: "/client/index/car",
}

function getURL(operate) {
  if (operate in URLS) {
    return HTTPS_HEAD + URLS[operate]
  } else
    throw Error("未定义的接口名")
}

function init_http_head() {
  try {
    HTTPS_HEAD = wx.getStorageSync('HTTPS_HEAD')
    if (HTTPS_HEAD == "")
      HTTPS_HEAD = DEFAULT_HEAD
    console.log(HTTPS_HEAD)
  } catch {
    HTTPS_HEAD = DEFAULT_HEAD
  }
}

function change_http_head(head) {
  head = head.trim()
  wx.setStorageSync('HTTP_HEAD', head)
  HTTPS_HEAD = head
}

function get_http_head(head) {
  return HTTPS_HEAD
}


function has_login() {
  if (buff_token != "")
    return true
  let local_token = wx.getStorageSync('token')
  if (local_token != "") {
    buff_token = local_token
    return true
  } else
    return false
}

function storeToken(token) {
  buff_token = token
  wx.setStorageSync('token', token)
}

function clearToken() {
  buff_token = ""
  wx.setStorageSync('token', "")
}

async function queryHistoryOrderList() {
  let url = getURL('order') + "?mode=HISTORY"
  try {
    const http_data = await new Promise(function (resolve, reject) {
      wx.request({
        url: url,
        method: "GET",
        header: {
          token: buff_token
        },
        success: (res) => {
          if (res.statusCode != 200) {
            reject(res.statusCode)
          } else {
            resolve(res.data)
          }
        },
        fail: (res) => {
          reject(res)
        }
      })
    })
    if (http_data.code == 0) {
      let order_array = http_data.data
      return {
        status: "success",
        res: order_array
      }
    } else {
      return {
        status: "fail",
        res: http_data
      }
    }
  } catch (error) {
    return {
      status: "error",
      res: error
    }
  }
}


async function login(account, password) {
  // 调用接口
  let url = getURL('login')
  try {
    const http_data = await new Promise(function (resolve, reject) {
      wx.request({
        method: 'POST',
        url: url,
        data: {
          account: account,
          password: password
        },
        success: (res) => {
          if (res.statusCode != 200) {
            reject(res.statusCode)
          } else {
            resolve(res.data)
          }
        },
        fail: (res) => {
          reject(res)
        }
      })
    })
    if (http_data.code == 0) {
      let recv_token = http_data.data.token
      storeToken(recv_token)
      return {
        status: "success"
      }
    } else return {
      status: "fail",
      res: http_data
    }
  } catch (error) {
    return {
      status: "error",
      res: error
    }
  }
}

async function register(account, password, nickName) {
  // 异步登录函数
  // 如果注册成功，直接视作登录
  let url = getURL('register')
  try {
    const http_data = await new Promise(function (resolve, reject) {
      wx.request({
        method: "POST",
        url: url,
        data: {
          account: account,
          password: password,
          name: nickName
        },
        success: (res) => {
          if (res.statusCode != 200)
            reject(res.statusCode)
          else
            resolve(res.data)
        },
        fail: (res) => {
          reject(res)
        }
      })
    })
    if (http_data.code == 0) {
      // 注册成功
      let recv_token = http_data.data.token
      // 将token保存在本地，同时也放入内存
      // 由于token只有在接口中可能使用，所以只存入该interface的全局变量
      storeToken(recv_token)
      return {
        status: "success"
      }
    } else return {
      status: "fail",
      res: http_data
    }
  } catch (error) {
    return {
      status: "error",
      res: error
    }
  }
}

async function queryUserInfo() {
  try {
    const http_data = await new Promise(function (resolve, reject) {
      let url = getURL('user_info')
      console.log(buff_token)
      wx.request({
        url: url,
        method: "GET",
        header: {
          token: buff_token
        },
        timeout: TIMEOUT,
        success: (res) => {
          if (res.statusCode == 200) {
            resolve(res.data)
          } else {
            reject(res)
          }
        },
        fail: (res) => {
          reject(res)
        }
      })
    })
    if (http_data.code == 0) {
      // 查询成功
      return {
        status: "success",
        res: http_data.data
      }
    } else return {
      status: "fail",
      res: http_data
    }
  } catch (error) {
    return {
      status: "error",
      res: error
    }
  }
}

function logout() {
  clearToken()
}

async function updateUserInfo(para) {
  // para内为需要修改的属性：
  //  如果只修改name，则只放入name
  //  如果修改密码，则要放入old_password与new_password两个部分
  //  也可以全修改，则以上三个字段都填入内容即可
  // 注意检测new_password的合法性

  // 检测格式是否正确
  let pwd_test = ('old_password' in para == 'new_password' in para)
  if (!pwd_test) {
    throw Error("参数错误，缺少一个密码字段")
  }
  try {
    let request_promise = new Promise(function (resolve, reject) {
      let url = getURL('user_info')
      wx.request({
        url: url,
        method: 'POST',
        header: {
          token: buff_token
        },
        data: para,
        timeout: TIMEOUT,
        success: (res) => {
          if (res.statusCode == 200)
            resolve(res.data)
          else
            reject(res)
        },
        fail: (res) => {
          reject(res)
        }
      })
    })
    const http_data = await request_promise
    if (http_data.code == 0) return {
      status: "success"
    }
    else return {
      status: "fail",
      res: http_data
    }
  } catch (error) {
    return {
      status: "error",
      res: error
    }
  }
}

// 1. 车辆名字、车牌号、当前电量、目标电量
// 2. 该车主拥有的汽车数量 
async function addVehicle(name, power_capacity, power_current) {
  let url = getURL('car')
  try {
    const http_data = await new Promise(function (resolve, reject) {
      wx.request({
        method: "POST",
        url: url,
        header: {
          token: buff_token
        },
        data: {
          name: name,
          power_current: power_current,
          power_capacity: power_capacity
        },
        success: (res) => {
          if (res.statusCode != 200)
            reject(res.statusCode)
          else
            resolve(res.data)
        },
        fail: (res) => {
          reject(res)
        }
      })
    })
    if (http_data.code == 0) {
      return {
        status: "success"
      }
    } else return {
      status: "fail",
      res: http_data
    }
  } catch (error) {
    return {
      status: "error",
      res: error
    }
  }
}

async function queryVehicle() {
  let url = getURL('car')
  try {
    const http_data = await new Promise(function (resolve, reject) {
      wx.request({
        method: "GET",
        url: url,
        header: {
          token: buff_token
        },
        success: (res) => {
          if (res.statusCode != 200)
            reject(res.statusCode)
          else
            resolve(res.data)
        },
        fail: (res) => {
          reject(res)
        }
      })
    })
    if (http_data.code == 0) {
      return {
        status: "success",
        res: http_data.data
      }
    } else return {
      status: "success",
      res: []
    }
  } catch (error) {
    return {
      status: "error",
      res: error
    }
  }
}

async function updateVehicle(car_id, name, power_capacity, power_current) {
  let url = getURL('car')
  try {
    const http_data = await new Promise(function (resolve, reject) {
      wx.request({
        method: "PATCH",
        url: url,
        header: {
          token: buff_token
        },
        data: {
          car_id: car_id,
          name: name,
          power_current: power_current,
          power_capacity: power_capacity
        },
        success: (res) => {
          if (res.statusCode != 200)
            reject(res.statusCode)
          else
            resolve(res.data)
        },
        fail: (res) => {
          reject(res)
        }
      })
    })
    if (http_data.code == 0) {
      return {
        status: "success"
      }
    } else return {
      status: "fail",
      res: http_data
    }
  } catch (error) {
    return {
      status: "error",
      res: error
    }
  }
}

async function createOrder(car_id, charge_mode, charge_kwh) {
  let url = getURL('order')
  try {
    const http_data = await new Promise(function (resolve, reject) {
      wx.request({
        method: "POST",
        url: url,
        header: {
          token: buff_token
        },
        data: {
          car_id: car_id,
          mode: charge_mode,
          apply_kwh: charge_kwh
        },
        success: (res) => {
          if (res.statusCode != 200)
            reject(res.statusCode)
          else
            resolve(res.data)
        },
        fail: (res) => {
          reject(res)
        }
      })
    })
    if (http_data.code == 0) {
      return {
        status: "success"
      }
    } else
      return {
        status: "fail",
        res: http_data
      }
  } catch (error) {
    return {
      status: "error",
      res: error
    }
  }
}

async function queryCurrentOrder(){
  let url = getURL('order') + "?mode=CURRENT"
  try {
    const http_data = await new Promise(function (resolve, reject) {
      wx.request({
        method: "GET",
        url: url,
        header: {
          token: buff_token
        },
        success: (res) => {
          if (res.statusCode != 200)
            reject(res.statusCode)
          else
            resolve(res.data)
        },
        fail: (res) => {
          reject(res)
        }
      })
    })
    if (http_data.code == 0) {
      return {
        status: "success",
        res: http_data.data
      }
    } else return {
      status: "fail",
      res: http_data
    }
  } catch (error) {
    return {
      status: "error",
      res: error
    }
  }
}

async function updateOrder(order_id, new_mode,apply_kwh) 
{
  let url = getURL('order')
  try {
    const http_data = await new Promise(function (resolve, reject) {
      wx.request({
        method: "PATCH",
        url: url,
        header: {
          token: buff_token
        },
        data: {
          id: order_id,
          mode: new_mode,
          apply_kwh: apply_kwh
        },
        success: (res) => {
          if (res.statusCode != 200)
            reject(res.statusCode)
          else
            resolve(res.data)
        },
        fail: (res) => {
          reject(res)
        }
      })
    })
    if (http_data.code == 0) {
      return {
        status: "success"
      }
    } else return {
      status: "fail",
      res: http_data
    }
  } catch (error) {
    return {
      status: "error",
      res: error
    }
  }
}

async function cancelOrder(order_id) 
{
  let url = getURL('order')
  try {
    const http_data = await new Promise(function (resolve, reject) {
      wx.request({
        method: "DELETE",
        url: url,
        header: {
          token: buff_token
        },
        data: {
          id: order_id,
        },
        success: (res) => {
          if (res.statusCode != 200)
            reject(res.statusCode)
          else
            resolve(res.data)
        },
        fail: (res) => {
          reject(res)
        }
      })
    })
    if (http_data.code == 0) {
      return {
        status: "success"
      }
    } else return {
      status: "fail",
      res: http_data
    }
  } catch (error) {
    return {
      status: "error",
      res: error
    }
  }
}

